package vn.cuhanh;

import java.util.Collection;
import java.util.List;

import vn.cuhanh.utils.ShareFacebook;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;

public class LoginFacebookActivity extends FragmentActivity {
	private static final int SPLASH = 0;
	private static final int SELECTION = 1;
	private static final int FRAGMENT_COUNT = SELECTION +1;

	private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
	
	public static final int LOGIN_OK = 1;
	public static final int LOGIN_CANCEL = 2;
	public LoginButton loginButton;
	public static boolean clickLoginAlready = false;
	
	//Ui handler
	private UiLifecycleHelper uiHelper;
	private Session.StatusCallback callback = 
			new Session.StatusCallback() {
		@Override
		public void call(Session session, 
				SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.test);
	    uiHelper = new UiLifecycleHelper(this, callback);
	    uiHelper.onCreate(savedInstanceState);

	    FragmentManager fm = getSupportFragmentManager();
	    fragments[SPLASH] = fm.findFragmentById(R.id.splashFragment);
	    fragments[SELECTION] = fm.findFragmentById(R.id.selectionFragment);

	    FragmentTransaction transaction = fm.beginTransaction();
	    for(int i = 0; i < fragments.length; i++) {
	        transaction.hide(fragments[i]);
	    }
	    transaction.commit();
	    loginButton = (LoginButton) findViewById(R.id.login_button);
//	    loginButton.setPublishPermissions(ShareFacebook.PUBLISH_PERMISSIONS);
	}
	private boolean isResumed = false;
	@Override
	public void onResume() {
	    super.onResume();
	    isResumed = true;
	    uiHelper.onResume();
	}

	@Override
	public void onPause() {
	    super.onPause();
	    isResumed = false;
	    uiHelper.onPause();
	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onDestroy() {
	    super.onDestroy();
	    uiHelper.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    uiHelper.onSaveInstanceState(outState);
	}
	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
	    // Only make changes if the activity is visible
	    if (isResumed) {
	        FragmentManager manager = getSupportFragmentManager();
	        // Get the number of entries in the back stack
	        int backStackSize = manager.getBackStackEntryCount();
	        // Clear the back stack
	        for (int i = 0; i < backStackSize; i++) {
	            manager.popBackStack();
	        }
	        if (state.isOpened()) {
	            // If the session state is open:
	            // Show the authenticated fragment
	        	
	            handleSessionOpen();
	        } else if (state.isClosed()) {
	            // If the session state is closed:
	            // Show the login fragment
        		onBackPressed();
	        }
	    }
	}
	@Override
	protected void onResumeFragments() {
	    super.onResumeFragments();
	    Session session = Session.getActiveSession();

	    if (session != null && session.isOpened()) {
	        // if the session is already open,
	        // try to show the selection fragment
	        handleSessionOpen();
	    } else {
	        // otherwise present the splash screen
	        // and ask the person to login.
	    	if(clickLoginAlready) {
        		onBackPressed();
        		return;
        	}
	    	clickLoginAlready = true;
	        showFragment(SPLASH, false);
	        loginButton.performClick();
	    }
	}
	@Override
	public void onBackPressed() {
//		Intent data = new Intent(this, ShareActivity.class);
//		startActivity(data);
		Intent data = new Intent();
		data.putExtra("result", LoginFacebookActivity.LOGIN_CANCEL);
		setResult(RESULT_CANCELED, data);
		finish();
	}
	public void handleSessionOpen() {
		Session session = Session.getActiveSession();
		List<String> permissions = session.getPermissions();
        if (!isSubsetOf(ShareFacebook.PUBLISH_PERMISSIONS, permissions)) {
            Session.NewPermissionsRequest newPermissionsRequest = new Session
                    .NewPermissionsRequest(this, ShareFacebook.PUBLISH_PERMISSIONS);
            
            session.requestNewPublishPermissions(newPermissionsRequest);
            return;
        }
        ShareFacebook.facebookName = null;
        ShareFacebook.facebookUserName = null;
		Intent data = new Intent();
		data.putExtra("result", LoginFacebookActivity.LOGIN_OK);
		setResult(RESULT_OK, data);
		finish();
	}
	
	private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
	    for (String string : subset) {
	        if (!superset.contains(string)) {
	            return false;
	        }
	    }
	    return true;
	}
	
	private void showFragment(int fragmentIndex, boolean addToBackStack) {
	    FragmentManager fm = getSupportFragmentManager();
	    FragmentTransaction transaction = fm.beginTransaction();
	    for (int i = 0; i < fragments.length; i++) {
	        if (i == fragmentIndex) {
	            transaction.show(fragments[i]);
	        } else {
	            transaction.hide(fragments[i]);
	        }
	    }
	    if (addToBackStack) {
	        transaction.addToBackStack(null);
	    }
	    transaction.commit();
	}
}
